<template>
  <div id="div" class="app-container" style="height:100%;">
    <el-container style="height: 100%; border: 1px solid #eee">
      <el-aside id="aside" width="auto" style="border-right: 1px solid #eee">
        <el-input
          class="elInput"
          placeholder="搜索"
          v-model="filterText">
        </el-input>
        <el-divider></el-divider>
<!--                  <el-tree
                    class="elTree"
                    :data="value1"
                    node-key="id"
                    show-checkbox
                    highlight-current
                    :default-expand-all="false"
                    :expand-on-click-node="false"
                    check-on-click-node
                    @check="addcom"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    ref="tree">
                  </el-tree>-->
        <el-tree
          ref="tree"
          node-key="id"
          :data="value1"
          @node-click="addcom"
          :props="defaultProps"
          :highlight-current="true"
          :filter-node-method="filterNode"
        >
          <span class="custom-tree-node" slot-scope="{ data }">
            <span class="treeText1">
              <span  v-if="data.children && data.children.length > 0"  class="el-icon-folder-opened" ></span>
              <svg-icon  v-else  class="nav-icon"  icon-class="tag"  :w="13"  :h="13" />
              {{ data.label }}
            </span>
            <span v-if="data.children && data.children.length > 0" class="treeText2" >({{ data.children.length }})</span>
          </span>
        </el-tree>

      </el-aside>
      <el-main style="padding: 0;">
        <el-row type="flex" justify="center">
          <el-col :span="22">
            <!-- 新增评定表 -->
            <el-row type="flex" justify="space-between" align="middle">
              <el-col :span="12">
                <div>
                  <h2>新 增 评 定 表</h2>
                </div>
              </el-col>
              <el-col :span="12" style="text-align: right;">
                <div class="grid-content">
                  <el-button type="danger" @click="restContainer">清空该页面内容</el-button>
                </div>
              </el-col>
            </el-row>
            <!-- 评定表名称 -->
            <el-row type="flex" justify="center" align="middle" style="border: 1px dashed #cccccc;border-radius: 10px;height: 80px;">
              <el-col :span="12">
                <div class="grid-content">
                  <span>评定表名称：</span>
                  <el-input v-model="formname" placeholder="输入评定表名称" style="width: 70%;"/>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content">
                  <el-button type="primary" style="" @click="openCategory = true">选择类别</el-button>：
                  <el-input v-model="cateName" readonly style="width: 50%;"/>
                </div>
              </el-col>
            </el-row>
            <!-- 组件容器渲染 -->
            <div v-for="(item,index) in hub ">
              <el-row type="flex" justify="space-between" align="middle" style="margin-top: 10px">
                <el-col :span="12">
                  <div class="grid-content">
                    <span v-show="item.isEdit">{{ item.oneTitle }}</span>
                    <el-input
                      type="text"
                      v-show="!item.isEdit"
                      v-model="item.titleVal"
                      ref="inputTitle"
                      @blur="handleBlur(index)"
                      style="width: 20%;"
                    />
                    <el-button @click="handleEdit(index)" icon="el-icon-edit" type="text" size="medium" style="margin-left: 10px"></el-button>
                    <!--                    <el-popconfirm
                                          title="确定往当前容器添加组件吗？"
                                          @confirm="handleIndex(index)"
                                        >
                                          <el-button slot="reference" type="text" size="medium" icon="el-icon-circle-plus-outline" style="margin-left: 10px"></el-button>
                                        </el-popconfirm>-->
                  </div>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <div class="grid-content">
                    <el-button @click="deleteArea(index)" class="red" type="text">删除该区域</el-button>
                    <el-button @click="clearContent(index)" class="red" type="text">清空该区域内容</el-button>
                  </div>
                </el-col>
              </el-row>
              <!-- 容器内组件渲染 -->
              <div class="containerClass" :class="{active:currentIndex==index}" @click="handleIndex(index)">
                <el-row v-for="assname in item.container" :assname="assname" class="component1">
                  <el-col :span="21" :offset="1">
                    <keep-alive>
                      <component
                        :is="assname"
                        :pgForm="{}"
                      ></component>
                    </keep-alive>
                  </el-col>
                  <el-col :span="1" :offset="1" style="margin-top: 10px;">
                    <el-popconfirm
                      title="确定删除这个组件吗？"
                      @confirm="delcom(assname,index)"
                    >
                      <el-button slot="reference" icon="el-icon-delete" size="mini" circle></el-button>
                    </el-popconfirm>
                  </el-col>
                </el-row>
              </div>
            </div>

            <!-- 新增模块内容 -->
            <el-row type="flex" justify="start" align="middle" style="margin-top: 10px;">
              <el-col :span="4">
                <div>
<!--                  <el-button @click="containerAdd" type="text" style="color: #409eff;font-size: 16px;font-weight: 700;">新增模块</el-button>-->
                  <el-button type="primary" @click="containerAdd">新增模块</el-button>
                  <el-dialog
                    title="请输入模块名"
                    :visible.sync="dialogVisible"
                    width="30%">

                    <el-row>
                      <el-col>
                        模块名：
                        <!--                        <el-input v-model="input" ref="saveTagInput" placeholder="请输入模块名" @keyup.enter.native="addContainer" style="width: 80%;"></el-input>-->
                        <el-autocomplete
                          popper-class="my-autocomplete"
                          v-model="input"
                          ref="saveTagInput"
                          clearable
                          :fetch-suggestions="querySearch"
                          placeholder="请输入模块名"
                          @keyup.enter.native="addContainer"
                        >
                          <template slot-scope="{ item }">
                            <div class="name">{{ item.value }}</div>
                          </template>
                        </el-autocomplete>
                      </el-col>
                    </el-row>

                    <span slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible = false,input = '' ">取 消</el-button>
                      <el-button type="primary" @click="addContainer">确 定</el-button>
                    </span>
                  </el-dialog>
                </div>
              </el-col>
<!--                <el-col :offset="1">-->
<!--                  <el-button @click="clearAll" type="text" style="color: #409eff;font-size: 16px;font-weight: 700">清空所有模块中的内容</el-button>-->
<!--                </el-col>-->
              <el-button type="primary" style="" @click="sortContainer">模块排序</el-button>

              <el-dialog title="选择类别" :visible.sync="openCategory" width="400px" center>
                <el-form ref="form" :model="form" label-width="80px">
                  <el-form-item label="所属类别" prop="pdType">
                    <el-select v-model="pdType" placeholder="请选择评定模板类别" @change="optionChange">
                      <el-option
                        v-for="cat in categoryList"
                        :key="cat.id"
                        :label="cat.cateName"
                        :value="cat.id"

                      />
                    </el-select>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button type="primary" @click="openCategory = false">确 定</el-button>
                </div>
              </el-dialog>

              <el-dialog
                title="请拖动重新排序"
                :visible.sync="sortDialogVisible"
                width="30%"
                :before-close="sortHandleClose">

                <el-tree
                  :data="data"
                  node-key="id"
                  default-expand-all
                  draggable
                  :allow-drop="allowDrop">
                </el-tree>

                <span slot="footer" class="dialog-footer">
                  <el-button @click="sortCancel">取 消</el-button>
                  <el-button type="primary" @click="sortAscertain">确 定</el-button>
                </span>
              </el-dialog>
            </el-row>
          </el-col>
        </el-row>

        <el-footer>
          <el-button type="primary" @click="submitass">提 交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-footer>
      </el-main>
    </el-container>
  </div>
</template>

<script>

import {addAssess, updateAssess,} from "@/api/gaoxin/assess";
import {getMenu} from "@/api/gaoxin/evaluate";
import {listCategory} from "@/api/system/category";


export default {
  name: "add",
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    //监视 hub 数组
    hub:{
      deep:true,
      handler(val){
        localStorage.setItem("todos",JSON.stringify(val));
      }
    },
    //当选择其他容器添加时，删除上一个容器在el-tree中的复选框勾选
    /*addIndex(newVal,oldVal){
      if (newVal !== oldVal) {
        this.hub[oldVal].nodeKeys.forEach(item => {
          this.$refs.tree.setChecked(item,false);
        });
        this.hub[newVal].nodeKeys.forEach(item => {
          this.$refs.tree.setChecked(item,true);
        });
      }
    }*/
  },
  created() {
    this.getMenuData();
    this.todos = JSON.parse(localStorage.getItem('todos'));
    this.getListCategory();
  },
  data() {
    return {
      input: '',
      todos: [],
      value1: [],

      //容器添加输入框提示
      restaurants: [],
      state: '',
      //要添加评估组件的容器序号
      addIndex: 0,

      //编辑模版一级标题
      isEdit: {
        isEdit1: true,
        isEdit2: true,
      },
      titleVal: {
        val1: '基本情况',
        val2: '功能评定',
      },
      //一级标题
      oneTitle: {
        basicCondition: '基本情况',
        functionAssess: '功能评定',
      },
      //容器样式
      containerClass: { change: false },
      currentIndex: 0,

      formname: "",
      cateName: "",
      remark: "",
      filterText: '',

      hub: [],
      // hub: JSON.parse(localStorage.getItem('todos')),

      assnames: [],
      asskeys: [],


      comlist: [],
      dialogVisible: false,
      sortDialogVisible: false,
      openCategory: false,
      pdType: 1,
      categoryList: [],
      form: {},
      //data 存放排序对话框数据
      data: [],
      sortDefaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      }
    }
  },

  methods: {
    //获取 左侧组件列表树
    getMenuData() {
      getMenu().then(response => {
        response.menu.forEach(item => {
          if(item.children.length !== 0) {
            this.value1.push(item);
          }
        });
      })
    },
    // 获取评定模板类别列表数据
    getListCategory() {
      listCategory().then(response => {
        this.categoryList = response.rows;
      });
    },
    //新增容器时 输入框带提示
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadAll() {
      return [
        { "value": "二、病情摘要" },
        { "value": "三、既往史" },
        { "value": "四、功能评定" },
        { "value": "五、入院时主要问题" },
        { "value": "六、康复治疗目标" },
        { "value": "七、康复治疗方案" },
        { "value": "八、注意事项" },
        { "value": "九、主管医师意见" },
        { "value": "十、上传附件" }
      ];
    },
    handleSelect(item) {
      console.log(item);
    },
    handleIconClick(ev) {
      console.log(ev);
    },

    // 改变节点的状态
    changeTreeNodeStatus(node) {
      node.expanded = this.expandAll
      for (let i = 0; i < node.childNodes.length; i++) {
        // 改变节点的自身expanded状态
        node.childNodes[i].expanded = this.expandAll;
        // 遍历子节点
        if (node.childNodes[i].childNodes.length > 0) {
          this.changeTreeNodeStatus(node.childNodes[i]);
        }
      }
    },
    //递归拼接父级过滤字符串
    getParent(node, name, key) {
      if(node.parent && node.parent.data[key]) {
        name += node.parent.data[key];
        return this.getParent(node.parent, name, key);
      }
      return name;
    },
    filterNode(value, data, node) {
      let names = this.getParent(node, node.data.label, 'label');
      let isName = names.includes(value);
      if(!value) {
        return true;
      }else if(isName){
        return true;
      }
    },

    //容器添加 el-dialog 打开
    containerAdd(){
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    //点击哪个容器就在哪个容器添加评估组件
    handleIndex(index){
      this.addIndex = index;
      this.currentIndex = index;
    },
    //编辑模板标题
    handleEdit(val) {
      this.hub[val].isEdit = false
      this.$nextTick(() => {
        this.$refs.inputTitle[val].focus()
      })
    },
    //当模板标题修改完毕 失去焦点时 触发
    handleBlur(val) {
      if(this.hub[val].titleVal === ''){
        this.$message('标题名不能为空！！！')
      }else{
        this.hub[val].isEdit = true
        this.hub[val].oneTitle = this.hub[val].titleVal
      }
    },
    //清空该页面内容
    clearAll() {
      let flag = 0;
      if(this.formname === ''){
        this.hub.forEach(item => {
          if(item.container.length > 0){
            flag = 1;
          }
        });
        if(flag === 0) {
          this.$modal.alert('容器为空，无需清空！');
          return;
        }
      }
      this.$confirm('确定清空所有容器中的组件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.hub.forEach(item => {
          item.container = [];
          item.nodeKeys.forEach(item => {
            const node = this.$refs.tree.getNode(item);
            if(node.childNodes.length > 0) {
              node.childNodes.forEach(item => {
                item.checked = false;
              });
              node.checked = false;
            }else{
              node.checked = false;
            }
          });
          item.nodeKeys = [];
        });
        this.$message({
          type: 'success',
          message: '清空成功!'
        });
      }).catch(() => {});
    },
    //清空该区域内容
    clearContent(index){
      if(this.hub[index].nodeKeys.length === 0){
        this.$message.warning('该区域无内容！');
        return;
      }
      this.$confirm('确定清空该区域？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.hub[index].container = [];
        this.hub[index].nodeKeys.forEach(item => {
          const node = this.$refs.tree.getNode(item);
          if(node.childNodes.length > 0){
            node.childNodes.forEach(item => {
              item.checked = false;
            })
            node.checked = false;
          }else{
            node.checked = false;
          }
        });
        this.hub[index].nodeKeys = [];
        this.$message({
          type: 'success',
          message: '清空成功!'
        });
      }).catch(() => {});

    },
    //删除该区域
    deleteArea(val) {
      this.$confirm('确定删除该区域？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(this.hub[val].container.length !== 0){
          this.hub[val].nodeKeys.forEach(item => {
            this.$refs.tree.setChecked(item,false);
          });
        }
        this.hub.splice(val,1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {});
    },

    //新增容器
    addContainer(){
      if(this.input === ''){
        this.$modal.msgWarning('模块名不能为空！')
        return;
      };
      this.hub.push({isEdit: true,titleVal: this.input,oneTitle: this.input,container: [],nodeKeys:[]});
      this.currentIndex = this.hub.length - 1;
      this.addIndex = this.hub.length - 1;
      this.input = '';
      this.dialogVisible = false;
    },
    //重置模块模板
    restContainer(){
      this.$confirm('确定清空页面所有内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.hub.forEach(item1 => {
          item1.nodeKeys.forEach(item2 => {
            this.$refs.tree.setChecked(item2,false);
          });
        });
        this.formname = '';
        this.hub = [];
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {});

    },
    cancel() {
      this.$tab.closeOpenPage("/setting/template/assess/index");
    },
    submitass() {
      if (this.formname == '') {
        this.$modal.msgWarning("请输入评估表名");
        return;
      };

      let ac1 = [];
      this.hub.forEach(item => {
        ac1.push({ titleName: item.titleVal, assConfig: item.container, assKeys: item.nodeKeys });
      });
      var form = {
        assessName: this.formname,
        assessConfig: JSON.stringify(ac1),
        pdType: this.pdType,//未分类
        createTime: null,
        updateTime: null
      };
      addAssess(form).then( response => {
        this.$modal.msgSuccess("新增成功");
        this.$tab.closeOpenPage("/setting/template/assess/index");
      });
    },

    //添加一个评估组件
    addcom(data, checkStatus) {  //data comlist数组中的组件 label（title） value（name） 对象
      //获取到当前点击的树节点
      const node = this.$refs.tree.getNode(data.id);
      if(node.childNodes.length > 0) {
        return;
      }
      //没有容器不可以添加组件
      if(this.hub.length === 0) {
        this.$message.warning('请先添加一个容器，才能选择评估组件添加！！！');
        node.checked = false;
        return;
      }

      try {
        this.hub.forEach(item1 => {
          item1.nodeKeys.forEach(item2 => {
            if(item2 === node.key) {
              this.$message.warning('请勿重复添加组件！！！');
              throw new Error("退出循环")
            }
          });
        });
      } catch (error) {
        return;
      }
      this.hub[this.addIndex].container.push(data.name);
      this.hub[this.addIndex].nodeKeys.push(node.key);
    },


    //删除一个评估组件
    delcom(com,conIndex) {
      this.visible = true;
      let index = this.hub[conIndex].container.indexOf(com);
      this.hub[conIndex].container.splice(index, 1);
      this.hub[conIndex].nodeKeys.splice(index, 1);
    },
    //打开排序对话框
    sortContainer() {
      this.sortDialogVisible = true;
      let n = 0;
      this.hub.forEach(item => {
        this.data.push({id: n++, label: item.titleVal});
      });
    },
    //拖拽时判定目标节点能否被放置。
    allowDrop(moveNode, inNode, type) {
      // 不能拖拽到级别里面
      if (type === "inner") return;
      if (moveNode.nextSibling === undefined) {
        return type === "prev";
      } else if (inNode.nextSibling === undefined) {
        return type === "next";
      } else if (moveNode.nextSibling.id !== inNode.id) {
        return type === "prev";
      } else {
        return type === "next";
      }
    },
    //排序对话框确定按钮方法
    sortAscertain() {
      this.sortDialogVisible = false;
      let list = [];
      this.data.forEach(item => {
        list.push(item.label);
      });
      let tempHub = [];
      this.hub.forEach(item1 => {
        const index = list.indexOf(item1.titleVal);
        tempHub[index] = JSON.parse(JSON.stringify(item1));
      });
      this.hub = JSON.parse(JSON.stringify(tempHub));
      this.data = [];
    },
    //排序对话框取消方法
    sortCancel() {
      this.sortDialogVisible = false;
      this.data = [];
    },
    //排序对话框关闭回调
    sortHandleClose() {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.data = [];
        })
        .catch(_ => {});
    },
    optionChange(val) {
      this.cateName = this.categoryList.find(item => item.id == val).cateName
    }
  },
  mounted() {
    this.todos.forEach(item1 => {
      item1.nodeKeys.forEach(item2 => {
        this.$refs.tree.setChecked(item2, true);
      });
    });
    this.restaurants = this.loadAll();
    this.$nextTick(() => {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      this.$refs.tree.setCheckedKeys(checkedKeys, true);
      // this.$refs.tree.setCurrentKey(19)
      // this.parentWidth = window.getComputedStyle(this.$refs.elCol).height; // 100px
      // console.log(this.parentWidth)
    });
  },

}
</script>

<style scoped>
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.component1 {
  border-bottom: 1px solid #bcc0c1 !important;
  margin-bottom: 20px;
  padding: 0 20px 20px 20px;
}
/deep/ .el-tree-node:focus > .el-tree-node__content {
  color: #6daffc !important;
}

#aside {
  height: 100%;
  background-color: #ffffff;
}

.elInput >>> .el-input__inner {
  margin-top: 1em;
  border-radius: 2em;
}

.elTree {
  margin-top: 1em;
  background-color: #f5f5f5;
}

.change {
  border: 2px solid red;
}

#div {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  min-height: 100%;
  height: auto;
}
.red{
  color: #ff4d40;
}
.active {
  border: 2px dashed red !important;
  min-height: 80px;
  border-radius: 10px;
  padding: 20px 0;
}
.containerClass {
  border: 1px dashed #ccc;
  min-height: 80px;
  border-radius: 10px;
  padding: 20px 0;
}

.el-footer {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 60px;
  margin-top: 20px;
}

.el-aside {
  /*background-color: #D3DCE6;*/
  color: #333;
  text-align: center;
  /*line-height: 200px;*/
}

.el-main {
  /*background-color: #E9EEF3;*/
  color: #333;
  /*text-align: center;*/
  /*line-height: 160px;*/
}

/*body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}*/


/*去掉el-main的滚动条*/
/*>>> .el-tabs--card {
  height: calc(100vh - 110px);
}

>>> .el-tab-pane {
  height: calc(100vh - 110px);
  overflow-y: auto;
}

>>> ::-webkit-scrollbar {
  width: 0 !important;
}

>>> ::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}*/
.my-autocomplete {
li {
  line-height: normal;
  padding: 7px;
}
.name {
  text-overflow: ellipsis;
  overflow: hidden;
}
.addr {
  font-size: 12px;
  color: #b4b4b4;
}

.highlighted .addr {
  color: #ddd;
}
}
</style>
